package ninethwork.two;

import java.util.*;

/**
 * @author ：chenzikang
 * @date ： 2020/4/14
 */

public class CountWords {
    public static void main(String[] args) {
        String sentence = "D:java MapDemo1 if it is to be it is up to me to delegate " +
                "8 distinct words detected:";

        //创建map
        Map<String, Integer> map = new TreeMap<>();

        //将字符串进行分割，得到数组str
        String[] str = sentence.split(" ");

        ///遍历数组str
        for (String key : str) {

            //当key>0时继续
            if (key.length() > 0) {

                //当key不在map中继续
                if (!map.containsKey(key)) {

                    //将数据存入map
                    map.put(key, 1);

                    //当key已经在map中了
                } else {

                    //得到此时的key的value值
                    int value = map.get(key);

                    //将value自增
                    value++;

                    //将新的key，value存入map，替换之前的
                    map.put(key, value);
                }


            }

        }

        //遍历map，得到结果
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "\t" + entry.getValue());
        }


    }
}
